import * as vscode from 'vscode';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';

/**
 * Webview 面板管理器
 */
export class WebviewPanelManager {
    private panel: vscode.WebviewPanel | undefined;
    private context: vscode.ExtensionContext;
    private configWatcher: vscode.FileSystemWatcher | undefined;

    constructor(context: vscode.ExtensionContext) {
        this.context = context;
    }

    /**
     * 创建或显示面板
     */
    public createOrShow() {
        const column = vscode.window.activeTextEditor
            ? vscode.window.activeTextEditor.viewColumn
            : undefined;

        // 如果面板已存在，则显示它
        if (this.panel) {
            this.panel.reveal(column);
            return;
        }

        // 创建新面板
        this.panel = vscode.window.createWebviewPanel(
            'cursorRestorePanel',
            'Cursor Restore',
            column || vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true,
                localResourceRoots: [this.context.extensionUri]
            }
        );

        // 设置 HTML 内容
        this.panel.webview.html = this.getHtmlContent(this.panel.webview);

        // 处理来自 webview 的消息
        this.panel.webview.onDidReceiveMessage(
            message => this.handleMessage(message),
            undefined,
            this.context.subscriptions
        );

        // 面板关闭时清理
        this.panel.onDidDispose(
            () => {
                this.panel = undefined;
                this.stopWatchingConfig();
            },
            null,
            this.context.subscriptions
        );

        // 加载当前配置
        this.loadConfig();

        // 开始监听配置文件变化
        this.startWatchingConfig();
    }

    /**
     * 处理来自 webview 的消息
     */
    private async handleMessage(message: any) {
        switch (message.command) {
            case 'saveCard':
                this.saveConfig({ card_code: message.value });
                vscode.window.showInformationMessage('激活码已保存');
                break;

            case 'saveToken':
                this.saveConfig({ token: message.value });
                vscode.window.showInformationMessage('Token已保存');
                break;

            case 'privilege':
                await this.executePrivilege();
                break;

            case 'renewal':
                await this.executeRenewal();
                break;

            case 'loadConfig':
                this.loadConfig();
                break;
        }
    }

    /**
     * 加载配置并发送到 webview
     */
    private loadConfig() {
        const config = this.getConfig();
        this.panel?.webview.postMessage({
            command: 'loadConfig',
            config: config
        });
    }

    /**
     * 执行一键特权
     */
    private async executePrivilege() {
        const config = this.getConfig();
        if (!config.card_code) {
            vscode.window.showWarningMessage('请先输入激活码');
            return;
        }

        vscode.window.showInformationMessage('正在执行一键特权...');
        // TODO: 调用 core.js 中的 activatePrivilege 方法
        this.panel?.webview.postMessage({
            command: 'privilegeResult',
            success: true,
            message: '一键特权功能开发中...'
        });
    }

    /**
     * 执行一键续杯
     */
    private async executeRenewal() {
        const config = this.getConfig();
        if (!config.token) {
            vscode.window.showWarningMessage('请先输入Token');
            return;
        }

        vscode.window.showInformationMessage('正在执行一键续杯...');
        // TODO: 调用 core.js 中的 executeRenewal 方法
        this.panel?.webview.postMessage({
            command: 'renewalResult',
            success: true,
            message: '一键续杯功能开发中...'
        });
    }

    /**
     * 获取配置
     */
    private getConfig(): { card_code?: string; token?: string } {
        const configPath = this.getConfigPath();
        if (fs.existsSync(configPath)) {
            try {
                return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
            } catch (error) {
                console.error('读取配置文件失败:', error);
            }
        }
        return {};
    }

    /**
     * 保存配置
     */
    private saveConfig(newConfig: { card_code?: string; token?: string }): void {
        const configPath = this.getConfigPath();
        const configDir = path.dirname(configPath);

        // 确保目录存在
        if (!fs.existsSync(configDir)) {
            fs.mkdirSync(configDir, { recursive: true });
        }

        // 读取现有配置
        let config: any = {};
        if (fs.existsSync(configPath)) {
            try {
                config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
            } catch (error) {
                console.error('读取配置文件失败:', error);
            }
        }

        // 合并新配置
        config = { ...config, ...newConfig };

        // 保存配置
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');

        // 保存后立即重新加载配置并更新页面
        // 注意：这里会触发文件监听器，但为了确保同步，我们手动调用一次
        setTimeout(() => {
            this.loadConfig();
        }, 100);
    }

    /**
     * 获取配置文件路径
     */
    private getConfigPath(): string {
        const homeDir = os.homedir();
        return path.join(homeDir, 'cursor-restore', 'config.json');
    }

    /**
     * 开始监听配置文件变化
     */
    private startWatchingConfig() {
        const configPath = this.getConfigPath();
        const configUri = vscode.Uri.file(configPath);

        // 创建文件监听器
        this.configWatcher = vscode.workspace.createFileSystemWatcher(
            new vscode.RelativePattern(path.dirname(configPath), path.basename(configPath))
        );

        // 监听文件变化
        this.configWatcher.onDidChange(() => {
            this.loadConfig();
        });

        // 监听文件创建
        this.configWatcher.onDidCreate(() => {
            this.loadConfig();
        });

        // 将监听器添加到订阅中
        this.context.subscriptions.push(this.configWatcher);
    }

    /**
     * 停止监听配置文件变化
     */
    private stopWatchingConfig() {
        if (this.configWatcher) {
            this.configWatcher.dispose();
            this.configWatcher = undefined;
        }
    }

    /**
     * 获取 HTML 内容
     */
    private getHtmlContent(_webview: vscode.Webview): string {
        return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cursor Restore</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            padding: 20px;
            background: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid var(--vscode-panel-border);
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header p {
            color: var(--vscode-descriptionForeground);
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            font-size: 14px;
            color: var(--vscode-input-foreground);
        }

        .form-group label .icon {
            margin-right: 6px;
        }

        .input-wrapper {
            position: relative;
        }

        .form-group input {
            width: 100%;
            padding: 12px 16px;
            background: var(--vscode-input-background);
            color: var(--vscode-input-foreground);
            border: 1px solid var(--vscode-input-border);
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: var(--vscode-focusBorder);
            box-shadow: 0 0 0 3px var(--vscode-focusBorder)33;
        }

        .form-group input::placeholder {
            color: var(--vscode-input-placeholderForeground);
        }

        .button-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 30px;
        }

        .btn {
            padding: 14px 24px;
            border: none;
            border-radius: 8px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-secondary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        .status {
            margin-top: 20px;
            padding: 12px 16px;
            border-radius: 6px;
            font-size: 13px;
            display: none;
        }

        .status.success {
            background: var(--vscode-testing-iconPassed)22;
            color: var(--vscode-testing-iconPassed);
            border-left: 4px solid var(--vscode-testing-iconPassed);
        }

        .status.error {
            background: var(--vscode-testing-iconFailed)22;
            color: var(--vscode-testing-iconFailed);
            border-left: 4px solid var(--vscode-testing-iconFailed);
        }

        .status.info {
            background: var(--vscode-testing-iconQueued)22;
            color: var(--vscode-testing-iconQueued);
            border-left: 4px solid var(--vscode-testing-iconQueued);
        }

        .footer {
            margin-top: 40px;
            text-align: center;
            color: var(--vscode-descriptionForeground);
            font-size: 12px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .spinning {
            animation: spin 1s linear infinite;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔄 Cursor Restore</h1>
            <p>轻松管理您的 Cursor 激活和续杯</p>
        </div>

        <form id="configForm">
            <div class="form-group">
                <label for="cardInput">
                    <span class="icon">🔑</span>
                    激活码 (Card)
                </label>
                <div class="input-wrapper">
                    <input
                        type="text"
                        id="cardInput"
                        placeholder="请输入您的激活码"
                        autocomplete="off"
                    />
                </div>
            </div>

            <div class="form-group">
                <label for="tokenInput">
                    <span class="icon">🔐</span>
                    Token
                </label>
                <div class="input-wrapper">
                    <input
                        type="text"
                        id="tokenInput"
                        placeholder="请输入您的 Token"
                        autocomplete="off"
                    />
                </div>
            </div>

            <div class="button-group">
                <button type="button" class="btn btn-primary" id="privilegeBtn">
                    <span>⭐</span>
                    <span>一键特权</span>
                </button>
                <button type="button" class="btn btn-secondary" id="renewalBtn">
                    <span>🔄</span>
                    <span>一键续杯</span>
                </button>
            </div>
        </form>

        <div id="status" class="status"></div>

        <div class="footer">
            <p>配置自动保存 • 数据存储在本地</p>
        </div>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        const cardInput = document.getElementById('cardInput');
        const tokenInput = document.getElementById('tokenInput');
        const privilegeBtn = document.getElementById('privilegeBtn');
        const renewalBtn = document.getElementById('renewalBtn');
        const statusDiv = document.getElementById('status');

        // 显示状态消息
        function showStatus(message, type = 'info') {
            statusDiv.textContent = message;
            statusDiv.className = 'status ' + type;
            statusDiv.style.display = 'block';

            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }

        // 保存激活码
        cardInput.addEventListener('blur', () => {
            const value = cardInput.value.trim();
            if (value) {
                vscode.postMessage({
                    command: 'saveCard',
                    value: value
                });
            }
        });

        // 保存 Token
        tokenInput.addEventListener('blur', () => {
            const value = tokenInput.value.trim();
            if (value) {
                vscode.postMessage({
                    command: 'saveToken',
                    value: value
                });
            }
        });

        // 一键特权
        privilegeBtn.addEventListener('click', () => {
            if (!cardInput.value.trim()) {
                showStatus('请先输入激活码', 'error');
                cardInput.focus();
                return;
            }

            privilegeBtn.disabled = true;
            const icon = privilegeBtn.querySelector('span:first-child');
            icon.classList.add('spinning');

            vscode.postMessage({ command: 'privilege' });
        });

        // 一键续杯
        renewalBtn.addEventListener('click', () => {
            if (!tokenInput.value.trim()) {
                showStatus('请先输入 Token', 'error');
                tokenInput.focus();
                return;
            }

            renewalBtn.disabled = true;
            const icon = renewalBtn.querySelector('span:first-child');
            icon.classList.add('spinning');

            vscode.postMessage({ command: 'renewal' });
        });

        // 接收来自扩展的消息
        window.addEventListener('message', event => {
            const message = event.data;

            switch (message.command) {
                case 'loadConfig':
                    if (message.config.card_code) {
                        cardInput.value = message.config.card_code;
                    }
                    if (message.config.token) {
                        tokenInput.value = message.config.token;
                    }
                    break;

                case 'privilegeResult':
                    privilegeBtn.disabled = false;
                    privilegeBtn.querySelector('span:first-child').classList.remove('spinning');
                    showStatus(message.message, message.success ? 'success' : 'error');
                    break;

                case 'renewalResult':
                    renewalBtn.disabled = false;
                    renewalBtn.querySelector('span:first-child').classList.remove('spinning');
                    showStatus(message.message, message.success ? 'success' : 'error');
                    break;
            }
        });

        // 页面加载时请求配置
        vscode.postMessage({ command: 'loadConfig' });
    </script>
</body>
</html>`;
    }
}

